package com.darco.darcoapp;

import eneter.messaging.endpoints.typedmessages.TypedResponseReceivedEventArgs;
import DARCOShared.requests.CreateAccountRequest;
import DARCOShared.requests.LoginRequest;
import DARCOShared.responses.CreateAccountResponse;
import DARCOShared.responses.ResponseBase;
import DARCOShared.responses.ResponseWrapper;
import DARCOShared.utils.Base64.InputStream;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.sax.TextElementListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

public class CreateAccount_Activity extends MessagingActivity implements OnClickListener {

	private static final int SELECT_PHOTO = 100;
	private MessagingManager mm;
	private Bitmap avatarBMP=null;
	private byte[] avatar= null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_account_);

		View done_button = findViewById(R.id.create_done_button);
		done_button.setOnClickListener(this);

		View upload_button = findViewById(R.id.create_upload_button);
		upload_button.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_account_, menu);
		return true;
	}


	void onPerformRequest(CreateAccountRequest req){
		//inizializzazione ...
		mm = new MessagingManager();
		mm.ConnectToServer(this); //mi connetto al server e mi iscrivo alle risposte
		mm.SendRequest(req, this); //invia una richiesta di info carta
		//qui sara necessario mostrare un popup di attesa, tipo "caricamento in corso" o roba simile
		Toast.makeText(getApplicationContext(), "Request sent!", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.create_done_button:
			EditText user_edit=(EditText) findViewById(R.id.create_username_editText);
			EditText email_edit=(EditText) findViewById(R.id.create_email_editText);
			EditText name_edit=(EditText) findViewById(R.id.create_name_editText);
			EditText surname_edit=(EditText) findViewById(R.id.create_surname_editText);
			EditText pwd1_edit=(EditText) findViewById(R.id.create_password_editText);
			EditText pwd2_edit=(EditText) findViewById(R.id.create_password2_editText);
			//ImageView avatar=(ImageView) findViewById(R.id.create_avatar_imageView);


			String user=user_edit.getText().toString().replace(" ", "");
			String email= email_edit.getText().toString().replace(" ", "");
			String name= name_edit.getText().toString().replace(" ", "");
			String surname= surname_edit.getText().toString().replace(" ", "");
			String pwd1= pwd1_edit.getText().toString();
			String pwd2= pwd2_edit.getText().toString();

			//controllo sui campi immessi
			if(user.compareTo("")==0 || email.compareTo("")==0 || name.compareTo("")==0 
					|| surname.compareTo("")==0 || pwd1.compareTo("")==0 || pwd2.compareTo("")==0 ){
				Toast.makeText(this, "you must complete all the fields", Toast.LENGTH_SHORT).show();
				break;
			}

			if(pwd1.compareTo(pwd2)!=0){
				Toast.makeText(this, "the passwords aren't equal", Toast.LENGTH_SHORT).show();
				break;
			}
			
			showLoadingDialog("sending your informations to server");
			//byte[] avatar= null; //TODO
			CreateAccountRequest create_req= new CreateAccountRequest(user,
					email, pwd1, name, surname, avatar);

			onPerformRequest(create_req);
			break;
		case R.id.create_upload_button:
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, SELECT_PHOTO);
			break;
		default:
			break;
		}

	}




	@Override
	void onResponseReceived(Object sender, TypedResponseReceivedEventArgs<ResponseWrapper> e) {
		ResponseBase respbase = e.getResponseMessage().getResponse();
		CreateAccountResponse create_resp= (CreateAccountResponse) respbase;
		switch(create_resp.getResponseType()){
		case CreateAccount:
			if(create_resp.error==false)
			{
				hideLoadingDialog();
				Toast.makeText(this, "Creation Successfull!", Toast.LENGTH_SHORT).show();
				//Intent i= new Intent(this,Login_Activity.class);
				//startActivity(i);
				finish();
			}

			else{
				Toast.makeText(this, "Creation Failed: "+create_resp.errorMessage, Toast.LENGTH_SHORT).show();
			}
			break;

		default: break;

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

		switch(requestCode) { 
		case SELECT_PHOTO:
			if(resultCode == RESULT_OK){
				showLoadingDialog("Elaborate image");

				Uri selectedImage = imageReturnedIntent.getData();
				/*String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(
	                               selectedImage, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();
				 */
				try {
					avatarBMP = decodeUri(selectedImage);


					ImageView avatarImageView = (ImageView) findViewById(R.id.create_avatar_imageView);
					/*

				int oldWidth = avatarBMP.getWidth();
				int oldHeight = avatarBMP.getHeight();
				int newWidth = avatar_width;  // whatever your desired width and height are
				int newHeight = avatar_height;

				// calculate the scale
				float scaleWidth = ((float) newWidth) / oldWidth;
				float scaleHeight = ((float) newHeight) / oldHeight;

				// create a matrix for the manipulation
				Matrix matrix = new Matrix();
				// resize the bit map
				matrix.postScale(scaleWidth, scaleHeight);

				// recreate the new Bitmap
				avatarBMP = Bitmap.createBitmap(avatarBMP, 0, 0,  oldWidth, oldHeight, matrix, true);
					 */
					hideLoadingDialog();

					if(avatarBMP!=null)
						avatarImageView.setImageBitmap(avatarBMP);

					ByteArrayOutputStream bos = new ByteArrayOutputStream();  
					avatarBMP.compress(CompressFormat.PNG, 0, bos);  
					avatar = bos.toByteArray();  
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {

		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 200;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE
					|| height_tmp / 2 < REQUIRED_SIZE) {
				break;
			}
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		// Decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);

	}
}
